package com.test.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yang on 17/3/6.
 */
public class Post {
    // 处理post请求
    public static String sendPost(String url, Map<String, String> params) throws IOException{

        List<BasicNameValuePair> pairs = null;
        if (params != null && !params.isEmpty()) {
            pairs = new ArrayList<>(params.size());
            for (String key : params.keySet()) {
                pairs.add(new BasicNameValuePair((key), params.get(key)));
            }
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 设置代理
        HttpHost proxy = new HttpHost("192.168.1.115", 8888);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(config);
        if (pairs != null && pairs.size() > 0) {
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));

        }

        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        httpPost.setHeader("User-Agent","RapidCalculation/3.0.0 (iPhone; iOS 8.1.2; Scale/2.00)");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClint error status code : " + statusCode);
        }

        HttpEntity entity = response.getEntity();
        String result;
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
            response.close();
            httpClient.close();
            return result;
        } else {
            return null;
        }

    }

    // 取返回值中的token
    public static String dataValue(String response) throws JSONException {
        JSONObject jsonObject = new JSONObject(response);
//        String data = jsonObject.optString("data");
//        JSONObject jsonObject1 = new JSONObject(data);
        String token = jsonObject.optString("token");
        return token;
    }
}